#include "UGLFontObj.h"

#include <boost/algorithm/string.hpp>

using namespace std;

TGLFontObj::~TGLFontObj()
{
	delete TWidth;
	for ( uint i=0;i<LineCount;i++ )
	{
		str[i] = "";
	}
	delete []str;
	str = NULL;
	delete Left;	
	delete Top	;	
	delete Right;	
	delete Bottom;	
}

TGLFontObj::TGLFontObj(TGLFontRef Font, const TRectangle& Rect, const HTextParams& HParams, const VTextParams& VParams, const char *text)
{
	font = Font;
	int height = Font->Height()*0.63;
	h= Font->Height();
    std::vector<std::string> lines;
	boost::split(lines, text, boost::is_any_of("\n"));
	LineCount = lines.size();

	TWidth	= new int[LineCount];
	str		= new string[LineCount];
	Left	= new int[LineCount];
	Top		= new int[LineCount];
	Right	= new int[LineCount];
	Bottom	= new int[LineCount];

	for ( uint i=0;i<LineCount;i++ )
	{
		str[i] = lines[i];
		TWidth[i]	= Font->TextWidth(str[i]);
		Left[i]		= Rect.Left;
		Top[i]		= Rect.Top;
		Right[i]	= Rect.Right ;
		Bottom[i]	= Rect.Bottom;

		if (HParams == TP_Right)
		{
			Left[i] = max(Left[i], Right[i] - TWidth[i]);
		}
		else
		if (HParams == TP_HCenter)
		{
			Left[i] = max(Left[i], (Right[i]+Left[i]- TWidth[i])/2);
		}

		if (VParams ==TP_Bottom)
		{
			Top[i] = max(Top[i], (int)(Bottom[i] - (lines.size()-i)*h));
		}
		else
		if (VParams ==TP_VCenter)
		{
			Top[i] = max(Top[i], (int)((Top[i]+Bottom[i]- h)/2 - (lines.size()-i-1)*h));
		}

		if (TWidth[i] > Right[i]-Left[i])
		{
			if (Font->GetEllipsisWidth() > Right[i]-Left[i])
			{
				str[i]="";
			}
			else
			{
				int WidthTill = 0;
				size_t j = 0;
				for (; j<str[i].length() && WidthTill+Font->GetCharWidth(str[i][j])+Font->GetEllipsisWidth() < Right[i]-Left[i]; j++)
					WidthTill = WidthTill+Font->GetCharWidth(str[i][j]);

				str[i].erase(j, str[i].length()-j);
				str[i] = str[i]+ ellipsis;
			}
		}


	}
}
	
void TGLFontObj::Draw()
{

	glPushAttrib( GL_LIST_BIT | GL_CURRENT_BIT  | GL_ENABLE_BIT | GL_TRANSFORM_BIT );
	glMatrixMode( GL_MODELVIEW );
	glEnable( GL_TEXTURE_2D );
	glDisable( GL_DEPTH_TEST );
	glEnable( GL_BLEND );

	glListBase( font->Getlist_base() );
	glPushMatrix();

	for ( uint i=0;i<LineCount;i++ )
	{
		glLoadIdentity();
		glTranslatef( Left[i], Top[i] + h*(i+1) , 0 );
		glCallLists( str[i].length(), GL_UNSIGNED_BYTE, str[i].c_str() );
	}
	glPopMatrix();

	glPopAttrib();
}
